package zoschina.app.ivan.starweather.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Locale;

import zoschina.app.ivan.starweather.model.City;
import zoschina.app.ivan.starweather.model.Weather;
import zoschina.app.ivan.starweather.model.WeatherInfo;

/**
 * Created by Ivan on 2015/8/24.
 */
public class Utility {


    public static void saveWeatherInfo(Context context,WeatherInfo weatherInfo){
        SharedPreferences.Editor editor= PreferenceManager.getDefaultSharedPreferences(context).edit();

        editor.putBoolean("avaliable", true);
        editor.putString("city_name",weatherInfo.getCity().getCityName());
        editor.putString("today_high_temp",weatherInfo.getToday().getHighTemp());
        editor.putString("today_low_temp",weatherInfo.getToday().getLowTemp());
        editor.putString("today_weather_desp",weatherInfo.getToday().getDesp());
        editor.putString("date",weatherInfo.getDate());
        editor.putString("time",weatherInfo.getTime());
        editor.commit();
    }

    public static String requestWeatherInfo(String cityId) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        String httpUrl = "http://apis.baidu.com/apistore/weatherservice/recentweathers";
        httpUrl = httpUrl + "?cityId=" + cityId;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("apikey", "d1b8f94688ce775bf6b8755a661d2e9d");

            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void SaveData(Context context,String label,String data){
        if(context==null|| TextUtils.isEmpty(label)||TextUtils.isEmpty(data)){
            return;
        }

        SharedPreferences.Editor editor= PreferenceManager.getDefaultSharedPreferences(context).edit();
        editor.putString(label,label);
    }


}

